from glob import glob
import xlsxwriter
import pandas as p
import numpy as np
import sys

#Collect specific model name information
def getModelName(file):
    return file[file.index('-')+1:file.index('.xlsx')]
#Determine what type of confidence set
def determineCase(pVals, alpha):
    diff = np.array(pVals)-alpha

    leftPos = diff[0]>0
    rightPos = diff[-1] > 0

    everNeg = np.sum(diff<0)>0

    if(not everNeg):
        r = 'unbounded'
    else:
        if(leftPos and rightPos):
            r = 'disjoint'
        elif(leftPos):
            r = 'right-bounded'
        elif(rightPos):
            r = 'left-bounded'
        else:
            r = 'bounded'
    return r
#Determine bounds of confidence set at a given confidence level
def getConfidenceSetBounds(nullValueData, alpha=0.05):
    pVals = nullValueData['P-Value']
    nullVals = nullValueData['Null Beta Value']
    case = determineCase(pVals, alpha)
    if(case=='unbounded'):
        bounds = (-np.inf, np.inf)
    elif(case=='disjoint'):
        failingSet = nullVals[pVals < alpha]
        leftIndex = min(failingSet.index)-1
        rightIndex = max(failingSet.index) + 1
        bounds = (-np.inf, nullVals.iloc[leftIndex], nullVals.iloc[rightIndex], np.inf)
    elif(case=='bounded'):
        passingSet = nullVals[pVals>alpha]
        bounds = (min(passingSet), max(passingSet))
    elif (case == 'left-bounded'):
        failingSet = nullVals[pVals < alpha]
        bounds = (min(failingSet), np.inf)
    elif (case == 'right-bounded'):
        failingSet = nullVals[pVals < alpha]
        bounds = (-np.inf, max(failingSet))


    return case, bounds

#Collect all files with a given file patter
pattern = 'Tables/iv-*.xlsx'

if(not sys.platform=='darwin'):
    pattern = 'Tables\iv-*.xlsx'

files = glob(pattern)

#Save the joint file
fileName = 'Tables/iv.xlsx'

if(not sys.platform=='darwin'):
    fileName = 'Tables\iv.xlsx'

#Write information
wb = xlsxwriter.Workbook(fileName, {'nan_inf_to_errors': True})
nullSheet = 'NullValueTests'
estSheet = 'JointResults'
for file in files:
    try:
        modelName = getModelName(file)
        nullValueData = p.read_excel(file, nullSheet)
        estData = p.read_excel(file, estSheet, header=None)
        tempSheet = wb.add_worksheet(modelName)
        tempSheet.write_column('A1', list(estData.iloc[:,0]))
        tempSheet.write_column('B1', list(estData.iloc[:,1]))

        i = 0
        nullCols = ['H', 'I', 'J']
        for col in nullValueData.columns:
            tempSheet.write(nullCols[i]+'1', col)
            tempSheet.write_column(nullCols[i]+'2', nullValueData[col])
            i+=1

        cs95Type, cs95 = getConfidenceSetBounds(nullValueData, .05)
        cs90Type, cs90 = getConfidenceSetBounds(nullValueData, .1)

        rows, cols = estData.shape

        tempSheet.write(rows, 0, '95% Confidence Set')

        tempSheet.write(rows + 1, 0, '90% Confidence Set')


        tempSheet.write_row(rows, 1, cs95)

        tempSheet.write_row(rows + 1, 1, cs90)
    except ValueError:
        print(f'{file} does not conform to format requirements.')




wb.close()